package com.xianyun.site.support.executor.filter.sms;

import com.xianyun.common.core.filter.Filter;
import com.xianyun.common.core.filter.FilterInvoker;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.site.support.common.constant.MessageConstants;
import com.xianyun.site.support.common.exception.SmsErrorCode;
import com.xianyun.site.support.common.exception.SmsException;
import com.xianyun.site.support.convertor.SmsConvertor;
import com.xianyun.site.support.domain.model.SmsMessage;
import com.xianyun.site.support.dto.SmsReceiveCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author mac_zyj
 *  一分钟内不能重复发送短信规则
 */
@Slf4j
@Component
public class SmsOneMinNotRepeatFilter implements Filter<SmsReceiveCmd> {


    private static final String SMS_ERROR_MESSAGE = "请不要一分钟内重复发送";

    private static final String CHECK = "校验";
    @Autowired
    private RedisService redisService;

    @Override
    public void doFilter(SmsReceiveCmd context, FilterInvoker nextFilter) {
        SmsMessage smsMessage = SmsConvertor.toEntity(context.getSmsMessage());
        String repeatCheckKey = smsMessage.getRedisCheckKey(MessageConstants.REPEAT_CHECK);
        if(null!=redisService.getCacheObject(repeatCheckKey)&&
                CHECK.equals(context.getCheckParam().getSystemModel())){
            SmsException smsException=new SmsException(SmsErrorCode.SMS_ONE_MIN_NOT_REPEAT_ERROR,SMS_ERROR_MESSAGE);
            log.warn("SmsException with error code:{},error message:{}",smsException.getErrCode(),smsException.getMessage());
            throw smsException;
        }
        nextFilter.invoke(context);
    }
}
